namespace Cik.Gapi4Net.Domain.Input.UrlBuilder
{
    using System.Reflection;
    using System.Text;
    using Core.CustomAttribute;

    public abstract class UrlBuilderBase<T> : IUrlBuilder<T> where T : IEntity
    {
        public T Entity { get; set; }

        public virtual string BuildUrl()
        {
            var builder = new StringBuilder();

            var propertyInfos = Entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (var info in propertyInfos)
            {
                var attrs = info.GetCustomAttributes(typeof(UrlElementAttribute), true);

                if (attrs.Length == 0)
                {
                    continue;
                }

                var urlAttr = attrs[0] as UrlElementAttribute;

                builder.AppendFormat("{0}={1}&", urlAttr.Name, info.GetValue(Entity, null));
            }

            return builder.ToString().Substring(0, builder.ToString().Length - 1);
        }
    }
}